package cgl.sensorgrid.sopac.gps.filters;

import java.util.*;
import cgl.narada.event.*;
import cgl.sensorgrid.filters.*;
import java.io.FileWriter;
import cgl.sensorgrid.common.PropertyFile;
import java.text.SimpleDateFormat;
import java.io.*;

class RYORecorderFilter {
    public RYORecorderFilter() {
    }

    private Object syncObj1 = new Object();
    private List eventList = Collections.synchronizedList(new LinkedList());
    private String dataDir;
    private int timeWindow;
    private String gpsNetwork;
    static int runcount = 0;
    private FileOutputStream fos;
    private Calendar today;

    /**
     *
     * @param argsb String[]
     */
    public RYORecorderFilter(String[] argsb) {
        System.out.println("Number of arguments = " + argsb.length);
        if (argsb.length == 3) {
            if (argsb[0] != null && argsb[0].length() > 0) {
                this.timeWindow = Integer.parseInt(argsb[0]);
                System.out.println(
                        "[RYORecorderFilter] --> Time Window = " +
                        this.timeWindow);
            }
            if (argsb[1] != null && argsb[1].length() > 0) {
                this.gpsNetwork = argsb[1];
                System.out.println(
                        "[RYORecorderFilter] --> GPS Network = " +
                        this.gpsNetwork);
            }
            if (argsb[2] != null && argsb[2].length() > 0) {
                this.dataDir = argsb[2];
                System.out.println(
                        "[RYORecorderFilter] --> Data Directory = " +
                        this.dataDir);
                String fname = dataDir + "/" + gpsNetwork +
                                "-" +
                                cgl.sensorgrid.common.Tools.getDate(System.currentTimeMillis()) +
                                ".ryo";

                try {
                    System.out.println("Creating file " + fname);
                    fos = new FileOutputStream(fname);
                } catch (FileNotFoundException ex) {
                    ex.printStackTrace();
                }
            }

            today = Calendar.getInstance();
        }
    }


    /**
     *
     * @param event NBEvent
     */
    public void addEvent(NBEvent event) {
        synchronized (syncObj1) {
            eventList.add(event);
            if (eventList.size() == 1) {
                syncObj1.notify();
            }
        }
    }


    /**
     *
     * @param event NBEvent
     */
    public void run() {
        boolean running = true;
        try {
            while (running) {
                synchronized (syncObj1) {
                    if (eventList.size() == 0) {
                        syncObj1.wait();
                    }
                    NBEvent nbEvent = (NBEvent) eventList.remove(0);
                    byte[] data2 = nbEvent.
                                   getContentPayload();
                    if (data2 != null && data2.length > 0) {
                        processMessage(data2);
                    }
                }
            }
            return;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    static int eventcount = 0;

    /**
     *
     * @param data byte[]
     */
    public void processMessage(byte[] data) {
        try {

            if (pastMidnight()) {
                fos.flush();
                fos.close();

                String filePath = dataDir + "/" + this.gpsNetwork + "-" +
                                  cgl.sensorgrid.common.Tools.getDate(System.
                        currentTimeMillis()) +
                                  ".ryo";

                fos = new FileOutputStream(filePath, true);
            }

            eventcount++;

//            if(eventcount>=25){
                fos.write(data);
                fos.write("\n[EOF]\n".getBytes());
                fos.flush();
//                eventcount=0;
//            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     *
     * @return boolean
     */
    public boolean pastMidnight() {
        Calendar c = Calendar.getInstance();

        if(c.get(Calendar.DAY_OF_YEAR) > today.get(Calendar.DAY_OF_YEAR)){
            System.out.println("Date Changed.");
            today = c.getInstance();
            return true;
        }
        else{
            return false;
        }
    }

}


/**
 *
 * <p>Title: SensorGrid</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * @author Galip Aydin
 * @version 1.0
 */
public class RYORecorder extends Filter {

    public RYORecorder() {
    }

    private RYORecorderFilter r2a;

    public RYORecorder(String[] args, String[] argsb) {
        if (args == null || args.length == 0) {
            System.err.println(
                    "Incorrect number of arguments in RYORecorderFilter::Constructor...");
        } else {
            this.initialize(args);
            r2a = new RYORecorderFilter(argsb);
            r2a.run();
        }
    }

    public void onEvent(NBEvent nbEvent) {
        if (nbEvent.getContentPayload() != null) {
            if (r2a != null && nbEvent != null) {
                r2a.addEvent(nbEvent);
            }
        }
    }

    public static void main(String args[]) {
        if (args.length < 5) {
            System.out.println("Usage: java cgl.sensorgrid.sopac.gps.filters.RYORecorder commType nbHost nbPort subTopic timeWindow gpsNetwork dataDir");
            System.exit(0);
        }

        String commType = args[0];
        String nbHost = args[1];
        String nbPort = args[2];
        String subTopic = args[3];
        String timeWindow = args[4];
        String gpsNetwork = args[5];
        String dataDir = args[6];

//        String commType = "tcp";
//        String nbHost = "gf3.ucs.indiana.edu";
//        String nbPort = "5544";
//        String subTopic = "/SOPAC/GPS/CRTN_01/RYO";
//        String timeWindow = "24";
//        String gpsNetwork = "CRTN_01";
//        String dataDir = "/home/gaydin/sensorgrid/data/ryo";

        String[] argsa = {commType,
                         nbHost,
                         nbPort,
                         subTopic,
                         ""};

        String[] argsb = {timeWindow, gpsNetwork, dataDir};
        RYORecorder test = new RYORecorder(argsa, argsb);
    }
}
